/* eslint-disable default-case */
/* eslint-disable no-param-reassign */
import { message } from 'antd';
import {
  getEmpList,
  getEmpAccuList,
  delInsEmpList,
  delAccuEmpList,
  InsBeginUse,
  AccuBeginUse,
  InsEndUse,
  AccuEndUse,
  getRespList,
  assignRespIns,
  assignRespAcco,
  getUniCreditCode,
  getBankAccoList,
  getInsLsPkgList,
  getPlcyParam,
  bankAccountAdd,
  checkBefInsertIns,
  custInsInsertSave,
  custInsBeginUseSave,
  getAccuLsPkgList,
  checkBefInsertAccu,
  custAccuInsertSave,
  custAccuBeginUseSave,
  getCustInsDetail,
  getInjRatiosUpdate,
  insUpdateSave,
  getCustAccuDetail,
  accuUpdateSave,
  getInsRatioData,
  getDownloadInfo,
  getUploadProgress,
  uploadCustInsAcco,
  uploadCustAccuAcco,
} from '@/services/singlemanage';
import { getArryStringBySymbol } from '@/utils/utils';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

let insAccuType;
// 非常重要属性
const namespace = 'singlemanage';
const ModelAddEmp = {
  namespace,
  state: {
    activeKey: '1',
    formFieldsValue: {}, // 表单域
    expandForm: false, // 展开收起
    pageData: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    respList: [],
    respAllList: [{ userId: 'all', userName: '全部' }],
    insUpdateData: {}, // 社保回显的数据
    accuUpdateData: {}, // 公积金回显的数据
    pageRatioData: {
      // 企业工伤比例列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    batchQuery: {
      // 批量上传数据
      progressPercent: 0,
    },
    currentStep: 0,
    showProgress: false,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/custInsAcco/dowoloadErrorExist', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    valuesArr: [
      'custId',
      'accoName',
      'areaId',
      'state',
      'respId',
    ],
    tempType: null,
  },
  effects: {
    // 获取社保账户列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getEmpList, payload);
      const {
        pageArg: { currentPage, pageSizes },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: {},
          currentPage,
          pageSizes,
        },
      });
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSizes,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 获取公积金账户列表
    *fetchAccuList({ payload }, { call, put }) {
      const response = yield call(getEmpAccuList, payload);
      const {
        pageArg: { currentPage, pageSizes },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSizes,
        },
      });
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSizes,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 删除社保列表单个数据
    *delInsfetchList({ payload }, { call, put, select }) {
      const response = yield call(delInsEmpList, payload);
      if (response.success) {
        message.success('删除成功！');
        let values;
        yield select(state => {
          const currentPage = state.singlemanage.pageData.pagination.current;
          const pageSizes = state.singlemanage.pageData.pagination.pageSize;
          const pageArg = { currentPage, pageSizes };
          values = {
            pageArg,
          };
        });
        yield put({
          type: 'fetchList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '删除失败！'}`);
      }
    },
    // 删除公积金列表单个数据
    *delAccufetchList({ payload }, { call, put, select }) {
      const response = yield call(delAccuEmpList, payload);
      if (response.success) {
        message.success('删除成功！');
        let values;
        yield select(state => {
          const currentPage = state.singlemanage.pageData.pagination.current;
          const pageSizes = state.singlemanage.pageData.pagination.pageSize;
          const pageArg = { currentPage, pageSizes };
          values = {
            pageArg,
          };
        });
        yield put({
          type: 'fetchAccuList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '删除失败！'}`);
      }
    },
    // 社保账户启用
    *beginInsUse({ payload }, { call, put, select }) {
      const response = yield call(InsBeginUse, payload);
      if (response.success) {
        message.success('启用成功！');
        let values;
        yield select(state => {
          const currentPage = state.singlemanage.pageData.pagination.current;
          const pageSizes = state.singlemanage.pageData.pagination.pageSize;
          const pageArg = { currentPage, pageSizes };
          values = {
            pageArg,
          };
        });
        yield put({
          type: 'fetchList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '启用失败！'}`);
      }
    },
    // 公积金账户启用
    *beginAccuUse({ payload }, { call, put, select }) {
      const response = yield call(AccuBeginUse, payload);
      if (response.success) {
        message.success('启用成功！');
        let values;
        yield select(state => {
          const currentPage = state.singlemanage.pageData.pagination.current;
          const pageSizes = state.singlemanage.pageData.pagination.pageSize;
          const pageArg = { currentPage, pageSizes };
          values = {
            pageArg,
          };
        });
        yield put({
          type: 'fetchAccuList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '启用失败！'}`);
      }
    },
    // 社保账户停用
    *endInsUse({ payload }, { call, put, select }) {
      const response = yield call(InsEndUse, payload);
      if (response.success) {
        message.success('停用成功！');
        let values;
        yield select(state => {
          const currentPage = state.singlemanage.pageData.pagination.current;
          const pageSizes = state.singlemanage.pageData.pagination.pageSize;
          const pageArg = { currentPage, pageSizes };
          values = {
            pageArg,
          };
        });
        yield put({
          type: 'fetchList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '停用失败！'}`);
      }
    },
    // 公积金账户停用
    *endAccuUse({ payload }, { call, put, select }) {
      const response = yield call(AccuEndUse, payload);
      if (response.success) {
        message.success('停用成功！');
        let values;
        yield select(state => {
          const currentPage = state.singlemanage.pageData.pagination.current;
          const pageSizes = state.singlemanage.pageData.pagination.pageSize;
          const pageArg = { currentPage, pageSizes };
          values = {
            pageArg,
          };
        });
        yield put({
          type: 'fetchAccuList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '停用失败！'}`);
      }
    },
    // 获取负责人列表
    *fetchRespList({ payload }, { call, put }) {
      const response = yield call(getRespList, payload);
      const respAllList = [{ userId: 'all', userName: '全部' }];
      yield put({
        type: 'updateModelData',
        payload: {
          respList: [],
        },
      });
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            respList: response.data,
            respAllList: [...respAllList, ...response.data],
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 指派
    *assignResp({ payload }, { call, select }) {
      const activeKey = yield select(state => state.singlemanage.activeKey);
      const response = yield call(activeKey === '1' ? assignRespIns : assignRespAcco, payload);
      return response;
    },
    // 获取统一社会信用代码
    *getUniCreditCode({ payload }, { call }) {
      const response = yield call(getUniCreditCode, payload);
      return response;
    },
    // 获取银行账户信息
    *getBankAccoList({ payload }, { call }) {
      const response = yield call(getBankAccoList, payload);
      return response;
    },
    // 获取社保组合数据
    *getInsLsPkgName({ payload }, { call }) {
      const response = yield call(getInsLsPkgList, payload);
      return response;
    },
    // 五险是否合一
    *getQueryPlcyParam({ payload }, { call }) {
      const response = yield call(getPlcyParam, payload);
      return response;
    },
    // 新增银行开户行保存接口
    *bankAccountInsert({ payload }, { call }) {
      const response = yield call(bankAccountAdd, payload);
      return response;
    },
    // 提交前进一步的校验
    checkBefInsert:[
      function*({ payload }, { call }) {
      const response = yield call(checkBefInsertIns, payload);
      return response;
    },
    { type:'throttle',ms:10000 }
  ],
  // 社保新增提交数据接口
    custInsInsert:[
      function*({ payload }, { call }) {
        const response = yield call(custInsInsertSave, payload);
        return response;
      },
      { type:'throttle',ms:10000 }
    ],
    // 社保新增提交并启用接口
    custInsBeginUse:[
      function*({ payload }, { call }) {
        const response = yield call(custInsBeginUseSave, payload);
        return response;
      },
      { type:'throttle',ms:10000 }
  ],
    // 获取公积金组合数据
    *getAccuLsPkgName({ payload }, { call }) {
      const response = yield call(getAccuLsPkgList, payload);
      return response;
    },
    // 公积金--提交前进一步的校验
    checkBefAccuInsert:[
      function*({ payload }, { call }) {
      const response = yield call(checkBefInsertAccu, payload);
      return response;
    },
    { type:'throttle',ms:10000 }
  ],
  // 公积金新增提交数据接口
  custAccuInsert:[
    function* ({ payload }, { call }) {
      const response = yield call(custAccuInsertSave, payload);
      return response;
    },
    { type:'throttle',ms:10000 }
  ],
  // 公积金新增提交并启用接口
    custAccuBeginUse:[
      function*({ payload }, { call }) {
        const response = yield call(custAccuBeginUseSave, payload);
        return response;
      },
      { type:'throttle',ms:10000 }
    ],
    // 查社保修改的数据
    *getInsDetail({ payload }, { call, put }) {
      const response = yield call(getCustInsDetail, payload);
      if (response.success) {
        yield put({
          type: 'getInsUpdateObj',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '社保回显数据：服务端错误！'}`);
      }
      return response;
    },
    // 企业工伤比例的回显数据
    *getInjRatios({ payload }, { call }) {
      const response = yield call(getInjRatiosUpdate, payload);
      return response;
    },
    // 社保修改后提交接口
    insUpdateSubmit:[
      function* ({ payload }, { call }) {
      const response = yield call(insUpdateSave, payload);
      return response;
    },
    { type:'throttle',ms:10000 }
  ],
    // 查公积金修改的数据
    *getAccuDetail({ payload }, { call, put }) {
      const response = yield call(getCustAccuDetail, payload);
      if (response.success) {
        yield put({
          type: 'getAccuUpdateObj',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '公积金回显数据：服务端错误！'}`);
      }
      return response;
    },
    // 公积金修改后提交接口
    auucUpdateSubmit:[
      function* ({ payload }, { call }) {
      const response = yield call(accuUpdateSave, payload);
      return response;
    },
    { type:'throttle',ms:10000 }
  ],
    // 详情--企业工伤比例数据展示
    *getInjRatioPage({ payload }, { call, put }) {
      const response = yield call(getInsRatioData, payload);
      const {
        pageArg: { currentPage, pageSizes },
      } = payload;
      yield put({
        type: 'getRatioList',
        payload: {
          data: {},
          currentPage,
          pageSizes,
        },
      });
      if (response.success) {
        yield put({
          type: 'getRatioList',
          payload: {
            data: response.data,
            currentPage,
            pageSizes,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 获取下载模板fileId fileName
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfo, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      } else {
        message.warning(`${response.message || '服务端错误：获取下载模板失败！'}`);
      }
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },

    // 上传文件:批量进度
    uploadFileWithProgress:[
      function* ({ payload: { params, type } }, { call, put }) {
      try {
        const response = yield call(type === 1 ? uploadCustInsAcco : uploadCustAccuAcco, params);
        if (response.success) {
          yield put({
            type: 'setTempType',
            payload: { tempType: response.data && response.data.tempType },
          });
          // 不是100表示需要走队列
          if (response.data && response.data.successProp !== 100) {
            insAccuType = type;
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
            // 订阅成功后再触发进度条
            yield put({
              type: 'updateModelData',
              payload: { showProgress: true },
            });
          } else {
            yield put({
              type: 'handleBatchTask',
              payload:  {
                ...response.data,
                insAccuType: type,
              },
            });
          }
        } else {
          message.warning(response.message || '上传文件错误：服务器端错误');
        }

        // 无需返回response对象
      } catch (e) {
        console.error(e);
      }
    },
    { type:'throttle',ms:10000 }
  ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.singlemanage);
      const { tempType } = state;
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          tempType,
        };
        if (payload.insAccuType === 1) {
          resultInfo.errorUrl = '/csApi/custInsAcco/dowoloadErrorExist';
        } else {
          resultInfo.errorUrl = '/csApi/custAccuAcco/dowoloadErrorExist';
        }
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },

    // end-xxl
  },
  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSizes },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      list.map((item, index) => {
        if (item.respList && item.respList.length) {
          list[index].respNameList = getArryStringBySymbol(item.respList, 'respName');
        } else {
          list[index].respNameList = '全部';
        }
        return true;
      });
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize: pageSizes },
        },
      };
    },
    // 社保回显数据
    getInsUpdateObj(state, { payload }) {
      if (payload && payload.respList && payload.respList.length) {
        payload.respNameList = getArryStringBySymbol(payload.respList, 'respName');
      } else {
        payload.respNameList = '全部';
      }
      return {
        ...state,
        insUpdateData: payload,
      };
    },
    // 公积金回显数据
    getAccuUpdateObj(state, { payload }) {
      if (payload && payload.respList && payload.respList.length) {
        payload.respNameList = getArryStringBySymbol(payload.respList, 'respName');
      } else {
        payload.respNameList = '全部';
      }
      return {
        ...state,
        accuUpdateData: payload,
      };
    },
    // 详情--社保企业工伤比例
    getRatioList(
      state,
      {
        payload: { data, currentPage, pageSizes },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageRatioData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize: pageSizes },
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 清除社保组合id公积金组合id及缴纳险种
    updateClearData(state, { payload }) {
      const temp = state;
      temp.insUpdateData.plcyId = undefined;
      temp.insUpdateData.insKinds = undefined;
      temp.accuUpdateData.plcyId = undefined;
      return {
        ...state,
        ...payload,
      };
    },
    // 设置查询时保存的值
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    setTempType(state, { payload }) {
      return {
        ...state,
        tempType: payload.tempType,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: {
                  ...action.data,
                  insAccuType,
                }
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
}

export default ModelAddEmp;
